Code Example:
contract GasOptimization {
// Storage variable declaration (no initialization cost)
uint256 public storedData;
// Efficient data management
function updateData(uint256 newValue) external {
uint256 memoryData = newValue; // Use memory for calculations
storedData = memoryData; // Update storage once
}
}
Techniques:
Code Example - Variable Packing:
struct PackedData {
uint8 data1;
uint8 data2;
}
PackedData public packedData;
selfdestruct to refund 24,000 gas by removing the contract.Code Example:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;
contract GasRefundExample {
uint256 public value1;
uint256 public value2;
function updateValuesAndFreeStorageSlot(uint256 _newValue1, uint256 _newValue2) external {
value1 = _newValue1;
value2 = _newValue2;
assembly {
sstore(value1.slot, 0)
sstore(value2.slot, 0)
}
}
function destroyContract() external {
selfdestruct(payable(msg.sender));
}
}
bytes32 when possible: More gas-efficient for storing fixed-size data.Code Example:
contract VariablePacking {
bytes32 public fixedSizeData;
// Using bytes32 is cheaper than string
function setData(bytes32 _data) external {
fixedSizeData = _data;
}
}
Code Example:
contract Parent {
uint256 public parentVar;
constructor(uint256 _parentVar) {
parentVar = _parentVar;
}
}
contract Child is Parent {
uint256 public childVar;
constructor(uint256 _parentVar, uint256 _childVar) Parent(_parentVar) {
childVar = _childVar;
}
}
Code Example:
function sumValues(uint256[] memory values) external pure returns (uint256) {
uint256 sum;
for (uint256 i = 0; i < values.length; i++) {
sum += values[i];
}
return sum;
}
Code Example:
mapping(address => uint256) public balances;
function updateBalance(address user, uint256 amount) external {
balances[user] = amount;
}
private to save gas.Code Example:
contract EfficientVariables {
uint256 private myPrivateVar;
event ValueUpdated(uint256 newValue);
function updatePrivateVar(uint256 newValue) external {
myPrivateVar = newValue;
emit ValueUpdated(newValue);
}
}
Code Example:
contract FunctionOptimization {
address public owner;
constructor() {
owner = msg.sender;
}
function getDataExternal() external view returns (uint256) {
return 42;
}
function frequentlyCalledFunction() external pure returns (string memory) {
return "Hello!";
}
}
By incorporating gas optimization techniques like minimizing storage use, careful handling of memory, leveraging inheritance, and proper data type selection, Solidity developers can significantly reduce gas costs and improve contract efficiency.